﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using MedLink2011.Views.ClinicCharts.ViewModels;
using Telerik.Windows.Controls;
using System.Linq;
using System.Windows.Media;
using System.Windows.Printing;
using System.Collections.Generic;
using System.IO;
using Telerik.Windows.Data;
namespace MedLink2011.Views.ClinicCharts.WorkWithGrid
{
    public partial class ClinicChartsWorkWithGrid : Page
    {

        public ClinicChartsWorkWithGrid()
        {
            ClinicChartViewModel.DashLoad_PK = 0;
            LocalizationManager.Manager = new WorkWith.CustomLocalizationManager();
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {


        }
        

        
        public static int CClinicChart_Id;
        private void ObtainClinicChart_Id()
        {

            string a = ClinicChartDataGridTelerik.SelectedItem.ToString();
            int i = a.IndexOf(":") + 1;
            a = a.Substring(i);
            int dashLoadPk;
            int.TryParse(a, out dashLoadPk);
            ClinicChartViewModel.DashLoad_PK = dashLoadPk;
            CClinicChart_Id = dashLoadPk;
        }
        
                private void EditCurrentInNewWindowButton_Click(object sender, RoutedEventArgs e)
        {
                ObtainClinicChart_Id();
                if (CClinicChart_Id > 0)
                {
                    var frm = new ChildWindows.ClinicChartsCW();
                    frm.Show();
                    frm.Closed += new System.EventHandler(FrmClosed);
                }
        }

        void FrmClosed(object sender, System.EventArgs e)
        {
            
        }

        private static void Failed(object sender, NavigationFailedEventArgs e)
        {
            e.Handled = true;
            MessageBox.Show("Exception " + e.Exception);
        }
        
        private void GoToEvaluation_CardiosButtonClick(object sender, System.Windows.RoutedEventArgs e)
        {
            ObtainClinicChart_Id();
            if (CClinicChart_Id > 0)
            {
            Uri target = new Uri("/ClinicCharts/Controls/Evaluation_CardiosControl?ClinicChart_Id=" + ClinicChartViewModel.DashLoad_PK, UriKind.Relative);
            NavigationService.NavigationFailed += new NavigationFailedEventHandler(Failed);
             if (NavigationService != null) NavigationService.Navigate(target);
        }
        }
        private void GoToEvaluation_ConstitutionalsButtonClick(object sender, System.Windows.RoutedEventArgs e)
        {
            ObtainClinicChart_Id();
            if (CClinicChart_Id > 0)
            {
            Uri target = new Uri("/ClinicCharts/Controls/Evaluation_ConstitutionalsControl?ClinicChart_Id=" + ClinicChartViewModel.DashLoad_PK, UriKind.Relative);
            NavigationService.NavigationFailed += new NavigationFailedEventHandler(Failed);
             if (NavigationService != null) NavigationService.Navigate(target);
        }
        }
        private void GoToEvaluation_EntsButtonClick(object sender, System.Windows.RoutedEventArgs e)
        {
            ObtainClinicChart_Id();
            if (CClinicChart_Id > 0)
            {
            Uri target = new Uri("/ClinicCharts/Controls/Evaluation_EntsControl?ClinicChart_Id=" + ClinicChartViewModel.DashLoad_PK, UriKind.Relative);
            NavigationService.NavigationFailed += new NavigationFailedEventHandler(Failed);
             if (NavigationService != null) NavigationService.Navigate(target);
        }
        }
        private void GoToEvaluation_ExtremsButtonClick(object sender, System.Windows.RoutedEventArgs e)
        {
            ObtainClinicChart_Id();
            if (CClinicChart_Id > 0)
            {
            Uri target = new Uri("/ClinicCharts/Controls/Evaluation_ExtremsControl?ClinicChart_Id=" + ClinicChartViewModel.DashLoad_PK, UriKind.Relative);
            NavigationService.NavigationFailed += new NavigationFailedEventHandler(Failed);
             if (NavigationService != null) NavigationService.Navigate(target);
        }
        }
        private void GoToEvaluation_GastrosButtonClick(object sender, System.Windows.RoutedEventArgs e)
        {
            ObtainClinicChart_Id();
            if (CClinicChart_Id > 0)
            {
            Uri target = new Uri("/ClinicCharts/Controls/Evaluation_GastrosControl?ClinicChart_Id=" + ClinicChartViewModel.DashLoad_PK, UriKind.Relative);
            NavigationService.NavigationFailed += new NavigationFailedEventHandler(Failed);
             if (NavigationService != null) NavigationService.Navigate(target);
        }
        }
        private void GoToEvaluation_LymphsButtonClick(object sender, System.Windows.RoutedEventArgs e)
        {
            ObtainClinicChart_Id();
            if (CClinicChart_Id > 0)
            {
            Uri target = new Uri("/ClinicCharts/Controls/Evaluation_LymphsControl?ClinicChart_Id=" + ClinicChartViewModel.DashLoad_PK, UriKind.Relative);
            NavigationService.NavigationFailed += new NavigationFailedEventHandler(Failed);
             if (NavigationService != null) NavigationService.Navigate(target);
        }
        }
        private void GoToEvaluation_MuscsButtonClick(object sender, System.Windows.RoutedEventArgs e)
        {
            ObtainClinicChart_Id();
            if (CClinicChart_Id > 0)
            {
            Uri target = new Uri("/ClinicCharts/Controls/Evaluation_MuscsControl?ClinicChart_Id=" + ClinicChartViewModel.DashLoad_PK, UriKind.Relative);
            NavigationService.NavigationFailed += new NavigationFailedEventHandler(Failed);
             if (NavigationService != null) NavigationService.Navigate(target);
        }
        }
        private void GoToEvaluation_NecksButtonClick(object sender, System.Windows.RoutedEventArgs e)
        {
            ObtainClinicChart_Id();
            if (CClinicChart_Id > 0)
            {
            Uri target = new Uri("/ClinicCharts/Controls/Evaluation_NecksControl?ClinicChart_Id=" + ClinicChartViewModel.DashLoad_PK, UriKind.Relative);
            NavigationService.NavigationFailed += new NavigationFailedEventHandler(Failed);
             if (NavigationService != null) NavigationService.Navigate(target);
        }
        }
        private void GoToEvaluation_NeurosButtonClick(object sender, System.Windows.RoutedEventArgs e)
        {
            ObtainClinicChart_Id();
            if (CClinicChart_Id > 0)
            {
            Uri target = new Uri("/ClinicCharts/Controls/Evaluation_NeurosControl?ClinicChart_Id=" + ClinicChartViewModel.DashLoad_PK, UriKind.Relative);
            NavigationService.NavigationFailed += new NavigationFailedEventHandler(Failed);
             if (NavigationService != null) NavigationService.Navigate(target);
        }
        }
        private void GoToEvaluation_RespisButtonClick(object sender, System.Windows.RoutedEventArgs e)
        {
            ObtainClinicChart_Id();
            if (CClinicChart_Id > 0)
            {
            Uri target = new Uri("/ClinicCharts/Controls/Evaluation_RespisControl?ClinicChart_Id=" + ClinicChartViewModel.DashLoad_PK, UriKind.Relative);
            NavigationService.NavigationFailed += new NavigationFailedEventHandler(Failed);
             if (NavigationService != null) NavigationService.Navigate(target);
        }
        }
        private void GoToEvaluation_SkinsButtonClick(object sender, System.Windows.RoutedEventArgs e)
        {
            ObtainClinicChart_Id();
            if (CClinicChart_Id > 0)
            {
            Uri target = new Uri("/ClinicCharts/Controls/Evaluation_SkinsControl?ClinicChart_Id=" + ClinicChartViewModel.DashLoad_PK, UriKind.Relative);
            NavigationService.NavigationFailed += new NavigationFailedEventHandler(Failed);
             if (NavigationService != null) NavigationService.Navigate(target);
        }
        }
        private void GoToHereditary_IllnesButtonClick(object sender, System.Windows.RoutedEventArgs e)
        {
            ObtainClinicChart_Id();
            if (CClinicChart_Id > 0)
            {
            Uri target = new Uri("/ClinicCharts/Controls/Hereditary_IllnesControl?ClinicChart_Id=" + ClinicChartViewModel.DashLoad_PK, UriKind.Relative);
            NavigationService.NavigationFailed += new NavigationFailedEventHandler(Failed);
             if (NavigationService != null) NavigationService.Navigate(target);
        }
        }
        private void GoToClinicChartsButtonClick(object sender, System.Windows.RoutedEventArgs e)
        {
            ObtainClinicChart_Id();
            Uri target = new Uri("/ClinicCharts/Controls/ClinicChartsControl?ClinicChart_Id=" + ClinicChartViewModel.DashLoad_PK, UriKind.Relative);
            NavigationService.NavigationFailed += new NavigationFailedEventHandler(Failed);
             if (NavigationService != null) NavigationService.Navigate(target);
        }

 #region print Grid

        double offsetY;
        double totalHeight;
        Canvas canvas;
        RadGridView grid;

        private void printListButton_Click(object sender, RoutedEventArgs e)
        {
            offsetY = 0d;
            totalHeight = 0d;

            grid = new RadGridView();
            grid.DataContext = ClinicChartDataGridTelerik.DataContext;
            grid.ItemsSource = ClinicChartDataGridTelerik.ItemsSource;
            grid.RowIndicatorVisibility = Visibility.Collapsed;
            grid.ShowGroupPanel = false;
            grid.CanUserFreezeColumns = false;
            grid.IsFilteringAllowed = false;
            grid.AutoExpandGroups = true;
            grid.AutoGenerateColumns = false;

            foreach (GridViewDataColumn column in ClinicChartDataGridTelerik.Columns.OfType<GridViewDataColumn>())
            {
                GridViewDataColumn newColumn = new GridViewDataColumn();
                newColumn.DataMemberBinding = new System.Windows.Data.Binding(column.UniqueName);
                grid.Columns.Add(newColumn);
            }

            foreach (GridViewDataColumn column in grid.Columns.OfType<GridViewDataColumn>())
            {
                GridViewDataColumn currentColumn = column;

                GridViewDataColumn originalColumn = (from c in ClinicChartDataGridTelerik.Columns.OfType<GridViewDataColumn>()
                                                     where c.UniqueName == currentColumn.UniqueName
                                                        select c).FirstOrDefault();
                if (originalColumn != null)
                {
                    column.Width = originalColumn.ActualWidth;
                    column.DisplayIndex = originalColumn.DisplayIndex;
                }
            }

            StyleManager.SetTheme(grid, StyleManager.GetTheme(ClinicChartDataGridTelerik));

            grid.SortDescriptors.AddRange(ClinicChartDataGridTelerik.SortDescriptors);
            grid.GroupDescriptors.AddRange(ClinicChartDataGridTelerik.GroupDescriptors);
            grid.FilterDescriptors.AddRange(ClinicChartDataGridTelerik.FilterDescriptors);

            ScrollViewer.SetHorizontalScrollBarVisibility(grid, ScrollBarVisibility.Hidden);
            ScrollViewer.SetVerticalScrollBarVisibility(grid, ScrollBarVisibility.Hidden);

            PrintDocument doc = new PrintDocument();

            canvas = new Canvas();
            canvas.Children.Add(grid);

            doc.PrintPage += this.doc_PrintPage;
            doc.Print("ClinicChartDataGridTelerik print");
        }

        void doc_PrintPage(object sender, PrintPageEventArgs e)
        {
            e.PageVisual = canvas;

            if (totalHeight == 0)
            {
                totalHeight = grid.DesiredSize.Height;
            }

            Canvas.SetTop(grid, -offsetY);

            offsetY += e.PrintableArea.Height;
            e.HasMorePages = offsetY <= totalHeight;
        }

            #endregion "Print grid" 

         #region "Export to Excel"
        
        private void ClinicChartDataGridTelerik_ElementExporting(object sender, Telerik.Windows.Controls.GridViewElementExportingEventArgs e)
        {
            if (e.Element == ExportElement.HeaderRow || e.Element == ExportElement.FooterRow
    || e.Element == ExportElement.GroupFooterRow)
            {
                e.Background = Colors.White;
                e.Foreground = Colors.Black;
                e.FontSize = 20;
                e.FontWeight = FontWeights.Bold;
            }
            else if (e.Element == ExportElement.Row)
            {
                e.Background = Colors.LightGray;
                e.Foreground = Colors.Blue;
            }

            else if (e.Element == ExportElement.Cell &&
                e.Value != null && e.Value.Equals("Chocolade"))
            {
                e.FontFamily = new FontFamily("Verdana");
                e.Background = Colors.LightGray;
                e.Foreground = Colors.Blue;
            }
            else if (e.Element == ExportElement.GroupHeaderRow)
            {
                e.FontFamily = new FontFamily("Verdana");
                e.Background = Colors.LightGray;
                e.Height = 30;
            }
            else if (e.Element == ExportElement.GroupHeaderCell &&
                e.Value != null && e.Value.Equals("Chocolade"))
            {
                e.Value = "MyNewValue";
            }
            else if (e.Element == ExportElement.GroupFooterCell)
            {
                GridViewDataColumn column = e.Context as GridViewDataColumn;
                QueryableCollectionViewGroup qcvGroup = e.Value as QueryableCollectionViewGroup;

                if (column != null && qcvGroup != null && column.AggregateFunctions.Count() > 0)
                {
                    e.Value = GetAggregates(qcvGroup, column);
                }
            }

        }

        private void Export2ExcelButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            string extension = "";
            ExportFormat format = ExportFormat.Html;

                  
                    extension = "xls";
                    format = ExportFormat.Html;

           

            SaveFileDialog dialog = new SaveFileDialog();
            dialog.DefaultExt = extension;
            dialog.Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, "Excel");
            dialog.FilterIndex = 1;

            if (dialog.ShowDialog() == true)
            {
                using (Stream stream = dialog.OpenFile())
                {
                    GridViewExportOptions exportOptions = new GridViewExportOptions();
                    exportOptions.Format = format;
                    exportOptions.ShowColumnFooters = true;
                    exportOptions.ShowColumnHeaders = true;
                    exportOptions.ShowGroupFooters = true;

                    ClinicChartDataGridTelerik.Export(stream, exportOptions);
                }
            }
        }     

        private string GetAggregates(QueryableCollectionViewGroup group, GridViewDataColumn column)
        {
            List<string> aggregates = new List<string>();

            foreach (AggregateFunction f in column.AggregateFunctions)
            {
                foreach (AggregateResult r in group.AggregateResults)
                {
                    if (f.FunctionName == r.FunctionName && r.FormattedValue != null)
                    {
                        aggregates.Add(r.FormattedValue.ToString());
                    }
                }
            }

            return String.Join(",", aggregates.ToArray());
        }
        #endregion "Export to Excel"

    }
    }


